#include "CommunicateChannel.h"

#include <QDebug>
#include <thread>

#ifdef Q_OS_LINUX
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#endif

#ifdef Q_OS_WIN
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib") // Winsock Library
#endif

static void ReceiveData(void* arg) {
    CommunicateChannel* cc = (CommunicateChannel*)arg;
    if(!cc){
        return;
    }
    int64_t sock = cc->getSocketObj();
    if(sock < 0){
        return;
    }
    struct sockaddr_in srcAddr;
    int addrLen = sizeof(srcAddr);
    char buffer[1024];

    while (true)
    {
        // 存在问题，如果是自己拼包，那么问题不大
        int bytesReceived = recvfrom(sock, buffer, sizeof(buffer), 0,
                                     (struct sockaddr*)&srcAddr, (socklen_t*)&addrLen);
        if (bytesReceived > 0)
        {
            emit cc->emitRecvData(buffer, bytesReceived);
        }
    }
}

class CommunicateChannelPrivate : public QObject
{
public:
    explicit CommunicateChannelPrivate(QObject *parent = nullptr):QObject(parent){}

#ifdef Q_OS_WIN
    SOCKET s = SOCKET_ERROR;

#endif
#ifdef Q_OS_LINUX
    int64_t s = -1;
#endif
     struct sockaddr_in localAddr, groupAddr;
};

CommunicateChannel::CommunicateChannel(QObject *parent)
    : QObject(parent)
    ,d(new CommunicateChannelPrivate(this))
{
#ifdef Q_OS_WIN
    WSADATA wsa;

    // 初始化 Winsock
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
        qDebug() << "Failed. Error Code: " << WSAGetLastError();
        return ;
    }
#endif

    // 创建套接字
    if ((d->s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
        qDebug() <<"socket creation failed";
        return;
    }

    // 启动接收线程
    std::thread receiverThread(ReceiveData, this);
    receiverThread.detach(); // 分离线程，使其独立运行
}

CommunicateChannel::~CommunicateChannel()
{
#ifdef Q_OS_WIN
    closesocket(d->s);    
    WSACleanup();
#endif

#ifdef Q_OS_LINUX
    close(d->s);
#endif
}

bool CommunicateChannel::bindAddr(char* localIp, int16_t localPort, char* groupIp, int16_t groupPort)
{
    if(!localIp){
        qDebug() << "ip is null";
        return false;
    }

    // 设置本地ip和端口
    memset(&d->localAddr, 0, sizeof(d->localAddr));
    d->localAddr.sin_family = AF_INET;
    d->localAddr.sin_port = htons(localPort);
    d->localAddr.sin_addr.s_addr = htonl(INADDR_ANY);

#ifdef Q_OS_LINUX
    int SOCKET_ERROR = -1;
#endif

    // 绑定套接字
    if(bind(d->s, (struct sockaddr*)&d->localAddr, sizeof(d->localAddr)) == SOCKET_ERROR){
        qDebug()  << "Failed to bind socket" ;
        return false;
    }

    // 设置组播组地址
    if(groupIp)
    {
        d->groupAddr.sin_family = AF_INET;
        d->groupAddr.sin_port = htons(groupPort);
        d->groupAddr.sin_addr.s_addr = inet_addr(groupIp);
    }

    return true;
}

int CommunicateChannel::sendData(char* data, int dataLength)
{
    int sendResult = 0;

#ifdef Q_OS_LINUX
    int SOCKET_ERROR = -1;
#endif

    if ((sendResult = sendto(d->s, data, dataLength, 0, (struct sockaddr*)&d->localAddr, sizeof (d->localAddr))) == SOCKET_ERROR) {
        qDebug() << "Send failed";
    } else {
        qDebug() << "Data send success";
    }

    return sendResult;
}

bool CommunicateChannel::start()
{
    if (d->s < 0) {
        qDebug() << "Socket is not initialized.";
        return false;
    }

    // 加入组播组
    struct ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = d->groupAddr.sin_addr.s_addr;
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);

    if (setsockopt(d->s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq)) < 0) {
        qDebug() << "Failed to join multicast group.";
        return false;
    }

    return true;
}

bool CommunicateChannel::stop()
{
    if (d->s < 0) {
        qDebug() << "Socket is not initialized.";
        return false;
    }

    struct ip_mreq mreq;

    // 离开组播组
    mreq.imr_multiaddr.s_addr = d->groupAddr.sin_addr.s_addr;
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    if (setsockopt(d->s, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq)) < 0)
    {
        qDebug() <<"Failed to leave multicast group.";
        return false;
    }

    return true;
}

int64_t CommunicateChannel::getSocketObj()
{
    return d->s;
}
